package cms.simmytech.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtils {

	private static final String URL = "https://hqyapi.tcmapi.cn/api/payment/pay/partner";

	private static final int CONNECTION_TIMEOUT = 60000;

	private static final int SO_TIMEOUT = 60000;

	private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	// 构建唯一会话Id
	public static String getSessionId() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
	}

	public static String httpPostJson(String jsonString, String url, Map<String, String> headerMap) {
		String body = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setConnectionRequestTimeout(CONNECTION_TIMEOUT)
		        .setSocketTimeout(SO_TIMEOUT).setRedirectsEnabled(true).build();

		httpPost.setConfig(requestConfig);
		if (null != headerMap && headerMap.size() > 0) {
			for (String key : headerMap.keySet()) {
				httpPost.setHeader(key, headerMap.get(key));
			}
		}
		// httpPost.setHeader("Content-Type", "application/json");
		try {
			httpPost.setEntity(new StringEntity(jsonString, ContentType.create("application/json", "utf-8")));
			HttpResponse response = httpClient.execute(httpPost);
			body = EntityUtils.toString(response.getEntity());
			return body;
		}
		catch (Exception e) {
			e.printStackTrace();
			return body;
		}
		finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static HttpClientContext httpClientContext = null;
	static {
		httpClientContext = HttpClientContext.create(); // 创建上下文.用于共享sessionid
	}

	public static String post(Map<String, String> map, String url) {
		HttpClient client = HttpClients.createDefault(); // 获取链接对象.
		HttpPost post = new HttpPost(url); // 创建表单.
		ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();// 用于存放表单数据.

		// 遍历map 将其中的数据转化为表单数据
		for (Map.Entry<String, String> entry : map.entrySet()) {
			pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}

		try {
			// 对表单数据进行url编码
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
			post.setEntity(urlEncodedFormEntity);

			HttpResponse httpResponse = client.execute(post, httpClientContext);// 发送数据.提交表单
			String content = null;
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(httpResponse.getEntity());
			}
			return content;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String get(Map<String, String> map, String url) {
		HttpClient client = HttpClients.createDefault(); // 获取链接对象.
		StringBuilder stringBuilder = new StringBuilder(url);
		if (null != map && !map.isEmpty()) {
			stringBuilder.append(Constants.QUESTION_MARK);
			boolean firstPara = true;
			for (String key : map.keySet()) {
				if (firstPara) {
					stringBuilder.append(key).append(Constants.EQUAL_SIGN).append(map.get(key));
					firstPara = false;
				} else {
					stringBuilder.append(Constants.AND_MARK).append(key).append(Constants.EQUAL_SIGN).append(map.get(key));
				}
			}
		}
		logger.debug(stringBuilder.toString());
		HttpGet get = new HttpGet(stringBuilder.toString()); // 创建表单.
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setConnectionRequestTimeout(CONNECTION_TIMEOUT)
		        .setSocketTimeout(SO_TIMEOUT).setRedirectsEnabled(true).build();
		get.setConfig(requestConfig);
		try {

			HttpResponse httpResponse = client.execute(get, httpClientContext);// 发送数据.提交表单
			String content = null;
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(httpResponse.getEntity());
			}
			return content;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean checkUserIdWithHttpHeader(HttpServletRequest request, String id) throws IllegalStateException {
		boolean result = false;
		if (request.getHeader("User-Id").equals(id)) {
			result = true;
		}
		return result;
	}

	/**
	 * main函数.
	 * 
	 * @param args
	 *            启动参数
	 * @throws Exception
	 *             Exception
	 */
	public static void main(String... args) throws Exception {
		// System.out
		// .println(httpPostJson("{\"agent\":\"2300000000\",\"aid\":48,\"code\":\"123456\",\"phone\":\"13466760778\",\"plat\":1,\"pwd\":\"e10adc3949ba59abbe56e057f20f883e\"}",
		// "http://47.94.204.100:8080/cosmosweb/user/reg.do"));
		// Map<String, String> map = new HashMap<>();
		// map.put("data",
		// "{\"token\":\"uiyqr33aQXanBg9q3SI0+eCd4zaFFsSZILXL0FP+8vPTejpf81l+1kNMTXLecvxGXGsA6WcfP3+kKtsOntVjeg==77b8x3LAQymRGDFYz/hPU89d25KF3WejLpcrUheHMG+q9w7UagicdwWVog==\",\"version\":\"\",\"appChannel\":\"2\"}");
		// String content = post(map, Constant.PICC_ADDRESS);
		// System.out.println(content);
		Map<String, String> map = new HashMap<>();
		map.put("appid", "wx64e17f5f6839ea55");
		map.put("secret", "88e2e8b7e590396bae88da0389b9cf79");
		map.put("js_code", "021k591N1PXXO71r1Q0N1sZR0N1k591U");
		map.put("grant_type", "authorization_code");
		System.out
		        .println(get(null,
		                     "https://api.weixin.qq.com/sns/jscode2session?appid=wxa728fcf547cd114c&secret=e7284c1d28ab82081fc0261cdbf314b7&js_code=033atPx825uqIJ08XBx82qxCx82atPx7&grant_type=authorization_code"));
		// System.out.println(get(map,
		// "https://api.weixin.qq.com/sns/jscode2session"));
	}

}